package com.jhd.fuzhou.view.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.downloadmanager.manager.UpdateManager;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.util.CannotScrollViewPager;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DipAndDp;
import com.jhd.fuzhou.util.GetSupervisionInspectionTaskSituation;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.archive.ArchiveActivity;
import com.jhd.fuzhou.view.document.DocumentManageActivity;
import com.jhd.fuzhou.view.document.DocumentNoActivity;
import com.jhd.fuzhou.view.dossier.DossierActivity;
import com.jhd.fuzhou.view.knowledge.KnowledgeBaseActivity;
import com.jhd.fuzhou.view.mail.MailListOrgActivity;
import com.jhd.fuzhou.view.monitoring.OnlineMonitoringActivity;
import com.jhd.fuzhou.view.punishment.AdministrativePunishmentActivity;
import com.jhd.fuzhou.view.quantitative.QuantitativeActivity;
import com.jhd.fuzhou.view.random.DoubleRandomActivity;
import com.jhd.fuzhou.view.receipt.ReceiptManagementActivity;
import com.jhd.fuzhou.view.special.SpecialActivity;
import com.jhd.fuzhou.view.daily.DailySupervisionActivity;
import com.jhd.fuzhou.view.task.TaskActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.QA;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;
import com.jhd.fuzhou.vo.TaskSearch;
import com.jhd.fuzhou.vo.UserMessage;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends BaseActivity {
    private static final int INSTALL_PERMISS_CODE = 2;
    @BindView(R.id.btn_mine)Button btn_mine;
    @BindView(R.id.rv_task)RecyclerView rv_task;//最新任务
    @BindView(R.id.vp_function)
    CannotScrollViewPager vp_function;//最新任务
    //@BindView(R.id.rv_function)RecyclerView rv_function;//常用功能
    private Context context =this;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    public static SupervisionInspectionVo supervisionInspectionVo = new SupervisionInspectionVo();
    public static List<QA> qaList;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE","android.permission.CAMERA" };
    private int width;
    private String apkFile;
    private LayoutInflater layoutInflater;
    private List gridViews,catogarys;
    @BindView(R.id.radioGroup_index_fragment)RadioGroup radioGroup_index_fragment;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_main);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void processLogic() {
        verifyStoragePermissions(this);
        apkFile=context.getExternalFilesDir(null).getPath()+ File
                .separator + "M_DEFAULT_DIR/fuzhou.apk";
        if (application.getUserId() == null) {
            startActivity(new Intent(context, LoginActivity.class));
            finish();
        }else{
            new UpdateManager(context).checkUpdate(true);
            layoutInflater = getLayoutInflater();
            catogarys = new ArrayList();
            initViewPager();
            /*GridLayoutManager functionManager = new GridLayoutManager(context, 2,RecyclerView.HORIZONTAL,false);
            rv_function.setLayoutManager(functionManager);
            FunctionAdapter functionAdapter=new FunctionAdapter();
            rv_function.setAdapter(functionAdapter);*/

        }
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth()- DipAndDp.dip2px(context,40);
        String userId=application.getUserId();
        if(application.getUserId()!=null&&application.getDeptId()==null){
            getPersonInfo();
        }

    }
    private void getPersonInfo(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("sysUserId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getPersonInfo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            UserMessage userMessage= JSON.parseObject(jsonForResult.getData().toString(), UserMessage.class);
                            application.setName(userMessage.getName());
                            application.setGender(userMessage.getGender());
                            application.setAssistant(userMessage.getAssistant());
                            application.setBirthday(userMessage.getBirthday());
                            application.setCity(userMessage.getCity());
                            application.setCounty(userMessage.getCounty());
                            application.setCreateTime(userMessage.getCreateTime());
                            application.setCreateUser(userMessage.getCreateUser());
                            application.setDeptName(userMessage.getDeptName());
                            application.setDeptId(userMessage.getDeptId());
                            application.setId(userMessage.getId());
                            application.setIdNo(userMessage.getIdNo());
                            application.setJoinSuperviseWork(userMessage.getJoinSuperviseWork());
                            application.setMobileActivateStatus(userMessage.getMobileActivateStatus());
                            application.setMobileNo(userMessage.getMobileNo());
                            application.setMobileRegisterStatus(userMessage.getMobileRegisterStatus());
                            application.setOrgId(userMessage.getOrgId());
                            application.setOrgName(userMessage.getOrgName());
                            application.setProvince(userMessage.getProvince());
                            application.setStatus(userMessage.getStatus());
                            application.setSysUserId(userMessage.getSysUserId());
                            application.setUseSystem(userMessage.getUseSystem());
                            application.setLawEnforceNo(userMessage.getLawEnforceNo());
                            application.setOrgLevel(userMessage.getOrgLevel());
                            startActivity(new Intent(context,MainActivity.class));
                            finish();
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void checkPhoneVersion(){
        if(Build.VERSION.SDK_INT >= 26){
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if(!haveInstallPermission){
                Uri packageURI = Uri.parse("package:"+getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
                startActivityForResult(intent, INSTALL_PERMISS_CODE);
            }else{
                installApk(new File(apkFile));
            }
        }else{
            installApk(new File(apkFile));
        }
    }

    //定影GridView的Adapter

    public class MyGridViewAdapter extends BaseAdapter {
        private int page;private int[] image;private String[] name;
        public MyGridViewAdapter(int page, String[] name,int[] image) {
            this.page = page;
            this.image = image;
            this.name = name;
        }
        @Override
        public int getCount() {
            return image.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.item_function, null);
                viewHolder.tv_name =(TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.iv_image =(ImageView) convertView.findViewById(R.id.iv_image);
                viewHolder.linearLayout =(LinearLayout) convertView.findViewById(R.id.linearLayout);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();

            }
            viewHolder.iv_image.setImageResource(image[position]);
            viewHolder.tv_name.setText(name[position]);
            viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if("日常监督".equals(name[position])){//日常监督
                                supervisionInspectionVo.setSupervisionType(1);
                                startActivity(new Intent(context, DailySupervisionActivity.class));
                            }else if("双随机".equals(name[position])){//双随机
                                supervisionInspectionVo.setSupervisionType(2);
                                startActivity(new Intent(context, DoubleRandomActivity.class));
                            }else if("行政处罚".equals(name[position])){//行政处罚
                                startActivity(new Intent(context, AdministrativePunishmentActivity.class));
                            }else if("量化评级".equals(name[position])){//量化评级
                                startActivity(new Intent(context, QuantitativeActivity.class));
                                //UtilHelper.alertMsg(context, "量化评级","该功能暂未开通！");
                            }else if("专项监督".equals(name[position])){//专项监督
                                supervisionInspectionVo.setSupervisionType(3);
                                startActivity(new Intent(context, SpecialActivity.class));
                            }else if("通讯录".equals(name[position])){//通讯录
                                startActivity(new Intent(context, MailListOrgActivity.class));
                            }else if("档案管理".equals(name[position])){//档案管理
                                startActivity(new Intent(context, ArchiveActivity.class));
                            }else if("文书领用".equals(name[position])){//文书领用
                                startActivity(new Intent(context, DocumentNoActivity.class));
                            }else if("监测预警".equals(name[position])){//在线监测
                                startActivity(new Intent(context, OnlineMonitoringActivity.class));
                            }else if("知识库".equals(name[position])){//知识库
                                startActivity(new Intent(context, KnowledgeBaseActivity.class));
                            }else if("收文管理".equals(name[position])){//收文管理
                                startActivity(new Intent(context, ReceiptManagementActivity.class));
                            }else if("本底档案".equals(name[position])){//收文管理
                                startActivity(new Intent(context, DossierActivity.class));
                            }else if("文书管理".equals(name[position])){//文书管理
                                startActivity(new Intent(context, DocumentManageActivity.class));
                            }
                        }
                    });

            return convertView;
        }
        public class ViewHolder {
            public ImageView iv_image;
            public TextView tv_name;
            public LinearLayout linearLayout;
        }
    }

    public void initViewPager() {
        gridViews = new ArrayList();
        ///定义第一个GridView
        String[] name1=new String[]{"日常监督","双随机","行政处罚","量化评级","专项监督","监测预警","文书领用","收文管理"};
        String[] name2=new String[]{"档案管理","通讯录","知识库","本底档案","文书管理"};
        int[] image1=new int[]{R.mipmap.ic_daily_supervision,R.mipmap.ic_double_random,R.mipmap.ic_administrative_punishment,R.mipmap.ic_quantitative_rating,
                R.mipmap.ic_special_supervise,R.mipmap.ic_online_detection,R.mipmap.ic_document_number_collection,R.mipmap.ic_receipt_management};
        int[] image2=new int[]{R.mipmap.ic_file_management,R.mipmap.ic_mail_list,R.mipmap.ic_knowledge_base,R.mipmap.ic_dossier,R.mipmap.ic_document_manger};
        GridView gridView1 =(GridView) layoutInflater.inflate(R.layout.gridview, null);
        MyGridViewAdapter myGridViewAdapter1 = new MyGridViewAdapter(0,name1,image1);
        gridView1.setAdapter(myGridViewAdapter1);
        //定义第二个GridView
        GridView gridView2 = (GridView)layoutInflater.inflate(R.layout.gridview, null);
        MyGridViewAdapter myGridViewAdapter2 = new MyGridViewAdapter(1, name2,image2);
        gridView2.setAdapter(myGridViewAdapter2);
        gridViews.add(gridView1);
        gridViews.add(gridView2);
        RadioButton radioButton = (RadioButton)radioGroup_index_fragment.getChildAt(0);
        radioButton.setChecked(true);
        //定义viewpager的PagerAdapter
        vp_function.setAdapter(new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }
            @Override
            public int getCount() {
                return gridViews.size();
            }
            @Override
            public void destroyItem(ViewGroup container, int position,Object object) {
                container.removeView((View) gridViews.get(position));
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView((View) gridViews.get(position));
                return gridViews.get(position);
            }
        });
        //注册viewPager页选择变化时的响应事件
        vp_function.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int position) {
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
            @Override
            public void onPageSelected(int position) {
                radioGroup_index_fragment.clearCheck();
                RadioButton radioButton = (RadioButton)radioGroup_index_fragment.getChildAt(position);
                radioButton.setChecked(true);
            }

        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISS_CODE) {
            installApk(new File(apkFile));
        }else{
            checkPhoneVersion();
        }
    }

    private void installApk(File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(getApplicationContext(), "com.jhd.fuzhou.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
        startActivity(install);
    }

    @Override
    protected void onStart() {
        super.onStart();
        TaskSearch taskSearch=new TaskSearch();
        taskSearch.setIsHomepage("1");
        taskSearch.setIsFinish("0");
        //rv_task.addItemDecoration(new RecycleViewDivider(context, LinearLayoutManager.VERTICAL));
        GetSupervisionInspectionTaskSituation.getSupervisionInspectionTaskSituation(application,context,rv_task,taskSearch);
    }


    @OnClick({R.id.btn_mine,R.id.btn_task,R.id.lin_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_mine:
                startActivity(new Intent(context, MineActivity.class));
                finish();
                break;
            case R.id.btn_task:
                startActivity(new Intent(context, TaskActivity.class));
                finish();
                break;
            case R.id.lin_more:
                startActivity(new Intent(context, TaskActivity.class));
                finish();
                break;
        }
    }

    //然后通过一个函数来申请
    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*public class FunctionAdapter extends RecyclerView.Adapter<FunctionAdapter.ViewHolder> {
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_function, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.iv_image.setImageResource(image[position]);
            holder.tv_name.setText(name[position]);
            LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) holder.tv_name.getLayoutParams();
            //获取当前控件的布局对象
            params.width=width/5;//设置当前控件布局的高度width是屏幕宽度
            holder.linearLayout.setLayoutParams(params);//将设置好的布局参数应用到控件中
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(position==0){//日常监督
                        startActivity(new Intent(context, DailySupervisionActivity.class));
                    }else if((position==1)){//双随机
                        startActivity(new Intent(context, DoubleRandomActivity.class));
                    }else if((position==2)){//行政处罚
                        startActivity(new Intent(context, AdministrativePunishmentActivity.class));
                    }else if((position==3)){//量化评级
                        startActivity(new Intent(context, QuantitativeActivity.class));
                        //UtilHelper.alertMsg(context, "量化评级","该功能暂未开通！");
                    }else if((position==4)){//专项监督
                        startActivity(new Intent(context, SpecialActivity.class));
                    }else if((position==5)){//通讯录
                        startActivity(new Intent(context, MailListOrgActivity.class));
                    }else if((position==6)){//文档管理
                        startActivity(new Intent(context, ArchiveActivity.class));
                    }else if((position==7)){//文书领用
                        startActivity(new Intent(context, DocumentNoActivity.class));
                    }else if((position==8)){//在线监测
                        startActivity(new Intent(context, OnlineMonitoringActivity.class));
                    }else if((position==9)){//知识库
                        startActivity(new Intent(context, KnowledgeBaseActivity.class));
                    }else if((position==10)){//收文管理
                        startActivity(new Intent(context, ReceiptManagementActivity.class));
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return image.length;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView iv_image;TextView tv_name;LinearLayout linearLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.iv_image = itemView.findViewById(R.id.iv_image);
                this.tv_name = itemView.findViewById(R.id.tv_name);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }*/

}